<template>
  <div class="login-container">
    <div
        class="login-main"
        :class="{'login-success': success}"
    >
      <h2 class="login-title">欢迎使用代驾后台管理系统</h2>
      <el-form
          class="login-form"
          ref="form"
          :model="form"
          label-width="80px"
      >
        <el-form-item
            label="账号"
            prop="account"
            :rules="[{required: true, message:'请输入账号'}]"
        >
          <el-input v-model="form.account" placeholder="请输入账号"></el-input>
        </el-form-item>
        <el-form-item
            label="密码"
            prop="pwd"
            :rules="[{required: true, message: '请输入密码'}]"
        >
          <el-input
              v-model="form.pwd"
              type="password"
              placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item class="login-btn-container">
          <el-button
              class="login-btn"
              type="primary"
              :loading="loading"
              @click="login"
          >登录
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
/**
 * @Author: lifuzhao
 * @Date: 2019-07-11
 * @Project: driver
 */
import dayjs from 'dayjs'
import './login.less'

export default {
  name: "login"
  , data() {
    return {
      form: {
        account: process.env.NODE_ENV !== 'production' ? '123' : ''
        , pwd: process.env.NODE_ENV !== 'production' ? 'a111111' : ''
      }
      , success: false
      , loading: false
    }
  }
  , mounted() {
  }
  , methods: {
    login() {
      this.$refs.form.validate(async valid => {
        if (!valid) return
        this.loading = true
        let {token, grade, msg} = await this.$axios.post('/api/v1/token/admin', this.form).catch(err => ({
          msg: '，' + err.message
        }))
        let message = ''
            , type = ''
        this.loading = false
        if (token) {
          message = '登录成功'
          type = 'success'
          this.$store.commit('setToken', token)
          this.$store.commit('setGrade', grade)
          this.$store.commit('setUser', this.form.account)
          this.$store.commit('setLoginTime', dayjs().format('YYYY-MM-DD HH:mm:ss'))
        } else {
          message = '登录失败' + msg
          type = 'error'
        }
        this.success = type === 'success'
        this.$message({
          message: message
          , type: type
        })
        if (this.success) {
          await this.$fn.sleep(1000)
          this.$router.replace({
            path: '/order'
          })
        }
      })
    }
  }
}
</script>
